Racket String

创建

双引号(不可变)

通过双括号创建字符串。

string 方法(可变)

> (define wishy-washy (string 一堆字符) )

> wishy-washy 
"I am mutable"

> (string-set! wishy-washy 5 一个字符) 
> (string-set! wishy-washy 6 一个字符)

> wishy-washy
"I am a table"

其中:字符都用文字代替,否则博客生成器会执行失败。

string-copy(可变)

> (define mstr (string-copy "I am also mutable")) 
> (string-set! mstr 5 一个字符) 
> (string-set! mstr 6 一个字符) 
> mstr
"I am so mutable"

make-string(可变)

> (define exes (make-string 10 一个字符)) 
> (string-set! exes 5 一个字符) 
> exes
"XXXXXOXXXX"

字符串操作

string-append 拼接

> (string-append "Luke, " "I am " "your father!") 
"Luke, I am your father!"

string-ref 给定位置字符

> (string-ref "abcdef" 2) 

string-length

> (string-length wishy-washy) 
12

substring

; characters 7-11 "table"
> (substring wishy-washy 7 12) 

string-titlecase

使用string-titlecase函数可以将字符串中每个单词的第一个字符大写。

> (string-titlecase wishy-washy) 
"I Am A Table"

string-upcase

> (string-upcase "big") 
"BIG"

string-downcase

> (string-downcase "SMALL") 
"small"

字母顺序比较

要进行字母顺序的比较,请使用string<=?函数:

; alphabetical comparison 
> (string<=? "big" "small") 
#t

string=?

string=?函数用于测试两个字符串是否相等:

> (string=? "big" "small") 
#f

string-replace

The string-replace function replaces part of a string with another string:

> (define darth-quote "Luke, I am your father!") 
> (string-replace darth-quote "am" "am not")
"Luke, I am not your father!"

string-contains?

To test whether one string is contained within another, use string-contains?:

> (string-contains? darth-quote "Luke")
#t

> (string-contains? darth-quote "Darth")
#f

string-split

The string-split function can be used to split a string into tokens:

> (string-split darth-quote) 
'("Luke," "I" "am" "your" "father!")

> (string-split darth-quote ",")
'("Luke" " I am your father!")

string-trim

The string-trim function gets rid of any leading and/or trailing spaces:

> (string-trim " hello ")
"hello"

> (string-trim " hello " #:right? #f) 
"hello "

> (string-trim " hello " #:left? #f)
" hello"

类型转换

> (symbol->string 'FBI) 
"FBI"

> (string->symbol "FBI") 
'FBI

> (list->string '(字符x 字符y 字符z)) 
"xyz"

> (string->list "xyz")
'(字符x 字符y 字符z)

> (string->keyword "string->keyword") 
'#:string->keyword

> (keyword->string '#:keyword)
"keyword"

> (number->string pi) 
"3.141592653589793"

> (string->number "3.141592653589793") 3.141592653589793

格式化

> (format "let ~a = ~a" "x" 2)
"let x = 2"

在格式化语句中,˜a充当占位符。对于每个额外的参数,应该有一个占位符。请注意,数字2在嵌入到输出字符串之前会自动转换为字符串。

r函数

为了更好地控制输出,我们可以使用racket/format库中定义的˜r函数,该函数具有许多选项,可以用于将数字转换为字符串并控制数字的精度和其他输出特性。例如,要将π显示为四位小数,我们可以使用以下代码:

> (~r pi #:precision 4) 
"3.1416"

要将其右对齐,在一个宽度为20个字符的字段中,并在左侧用点号填充,我们执行以下操作:

> (~r pi #:min-width 20 #:precision 4 #:pad-string ".") 
"..............3.1416"

还有其他一些有用的以波浪号为前缀的字符串转换函数可用,例如˜a、˜v和˜s。


本文作者:Maeiee

本文链接:Racket String

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!


喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!